// we need to let this middleware take the public method first before
// running pass to the auth-middleware otherwise, it will not able to
// get to the next one
const { QUERY_NAME, MUTATION_NAME, AUTH_TYPE } = require('jsonql-constants')
const { resolveMethod, handleAuthMethods } = require('jsonql-resolver')

const { getDebug, extractParamsFromContract } = require('./lib')

const debug = getDebug('public-method-middleware')

// main export
module.exports = function(opts) {
  return async function(ctx, next) {
    const { isReq, resolverType, resolverName, payload, contract } = ctx.state.jsonql;
    // we pre-check if this is auth enable, if it's not then let the other middleware to deal with it
    if (isReq && opts.enableAuth) {
      if (resolverType === QUERY_NAME || resolverType === MUTATION_NAME) {
        let params = extractParamsFromContract(contract, resolverType, resolverName)
        if (params.public === true) {
          return resolveMethod(ctx, resolverType, opts, contract)
        }
      } else if (resolverType === AUTH_TYPE && resolverName === opts.loginHandlerName) {
        debug(`This is an auth ${opts.loginHandlerName} call`);
        return handleAuthMethods(ctx, resolverName, payload, opts, contract)
      }
    }
    await next()
  }
}
